package cn.wildfirechat.app.update;

import cn.wildfirechat.app.update.AppVersion;
import cn.wildfirechat.app.update.dto.VersionCheckRequest;
import cn.wildfirechat.app.update.dto.VersionCheckResponse;
import cn.wildfirechat.app.update.AppVersionMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class AppVersionService extends ServiceImpl<AppVersionMapper, AppVersion> {

    /**
     * 检查版本更新
     */
    public VersionCheckResponse checkVersion(VersionCheckRequest request) {
        // 获取最新版本
        AppVersion latestVersion = getLatestVersion(request.getPlatform());

        VersionCheckResponse response = new VersionCheckResponse();

        if (latestVersion == null) {
            response.setHasUpdate(false);
            response.setMessage("暂无版本信息");
            response.setShowNotification(false);
            return response;
        }

        // 比较版本号
        boolean hasUpdate = compareVersion(request.getCurrentVersionCode(), latestVersion.getVersionCode());
        response.setHasUpdate(hasUpdate);

        if (hasUpdate) {
            response.setLatestVersion(latestVersion.getVersionName());
            response.setVersionCode(latestVersion.getVersionCode());
            response.setDescription(latestVersion.getDescription());
            response.setUpdateContent(latestVersion.getUpdateContent());
            response.setDownloadUrl(latestVersion.getDownloadUrl());
            response.setPlayStoreUrl(latestVersion.getPlayStoreUrl());
            response.setFileSize(latestVersion.getFileSize());
            response.setMd5(latestVersion.getMd5());
            response.setUpdateType(latestVersion.getUpdateType());
            response.setPriority(latestVersion.getPriority());

            // 根据更新类型决定是否显示通知
            response.setShowNotification(shouldShowNotification(latestVersion.getUpdateType()));
            response.setMessage("发现新版本 " + latestVersion.getVersionName());
        } else {
            response.setMessage("当前已是最新版本");
            response.setShowNotification(false);
        }

        return response;
    }

    /**
     * 根据更新类型决定是否显示通知
     */
    private boolean shouldShowNotification(String updateType) {
        if (updateType == null) return true;

        switch (updateType) {
            case "RECOMMENDED":
                return true;  // 推荐更新，显示通知
            case "OPTIONAL":
                return true;  // 可选更新，显示通知
            case "NOTIFY_ONLY":
                return false; // 仅记录，不显示通知
            default:
                return true;
        }
    }

    /**
     * 获取最新版本
     */
    public AppVersion getLatestVersion(String platform) {
        QueryWrapper<AppVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("platform", platform)
                .eq("is_enabled", true)
                .orderByDesc("version_code")
                .last("LIMIT 1");
        return this.getOne(wrapper);
    }

    /**
     * 获取版本列表
     */
    public IPage<AppVersion> getVersionList(Page<AppVersion> page, String platform) {
        QueryWrapper<AppVersion> wrapper = new QueryWrapper<>();
        if (platform != null && !platform.isEmpty()) {
            wrapper.eq("platform", platform);
        }
        wrapper.orderByDesc("create_time");
        return this.page(page, wrapper);
    }

    /**
     * 添加版本
     */
    public boolean addVersion(AppVersion appVersion) {
        appVersion.setCreateTime(LocalDateTime.now());
        appVersion.setUpdateTime(LocalDateTime.now());

        if (appVersion.getIsEnabled() == null) {
            appVersion.setIsEnabled(true);
        }

        if (appVersion.getUpdateType() == null) {
            appVersion.setUpdateType("RECOMMENDED");
        }

        if (appVersion.getPriority() == null) {
            appVersion.setPriority(3); // 默认中等优先级
        }

        if (appVersion.getReleaseTime() == null) {
            appVersion.setReleaseTime(LocalDateTime.now());
        }

        return this.save(appVersion);
    }

    /**
     * 更新版本
     */
    public boolean updateVersion(AppVersion appVersion) {
        appVersion.setUpdateTime(LocalDateTime.now());
        return this.updateById(appVersion);
    }

    /**
     * 删除版本
     */
    public boolean deleteVersion(Long id) {
        return this.removeById(id);
    }

    /**
     * 启用/禁用版本
     */
    public boolean toggleVersion(Long id) {
        AppVersion version = this.getById(id);
        if (version != null) {
            version.setIsEnabled(!version.getIsEnabled());
            version.setUpdateTime(LocalDateTime.now());
            return this.updateById(version);
        }
        return false;
    }

    /**
     * 比较版本号
     */
    private boolean compareVersion(Long currentVersionCode, int latestVersionCode) {
        return latestVersionCode > currentVersionCode;
    }
}